package uit.shoeshop.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import uit.shoeshop.lib.Util;
import uit.shoeshop.model.LoginModel;

import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;

	private String username;
	private String password;
	private int err;
	private String action;
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
    public String execute() throws Exception {
    	LoginModel login = new LoginModel();
    	try{
    		if(getAction() != null){
    			Util.setLogin("login", 0, request);
    			response.sendRedirect("login.html");
    		}
    		
    		if(Util.getLogin("login", request) == 1) response.sendRedirect("managecategory.html");
    		
    		if(this.request.getMethod().equalsIgnoreCase("POST")){
        		if(getUsername() != null && getPassword() != null){
            		int checkLogin =  login.checkLogin(getUsername(), getPassword());
            		if(checkLogin == 0)
            			response.sendRedirect("login.html?err=1");
            		else if(checkLogin == 1){
            			Util.setLogin("login", 1, request);
            			response.sendRedirect("managecategory.html");
            			return SUCCESS;
            		}
        		}
        	}    	
    	}catch(Exception e){
    		return ERROR;
    	}finally{
    		login = null;
    	}
    	
        return SUCCESS;
    }

	public void setUsername(String username) {
		this.username = username;
	}

	public String getUsername() {
		return username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}

	public void setErr(int err) {
		this.err = err;
	}

	public int getErr() {
		return err;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public String getAction() {
		return action;
	}

}
